import { Button, Form, Input, Space, message } from "antd";
import React from "react";
import "./login.css";
import { getMenu } from "../../api";
import { useNavigate,Navigate, Router} from "react-router-dom";
import { login } from "../../api";
import axios from 'axios'; 
const Login = () => {
    const navigate =useNavigate()
    // //在登录状态下，需要跳转到home
    // if(localStorage.getItem()){
    //     return <Navigate to="/home" replace></Navigate>
    // }
  const handleSubmit = async (val) => {
    if (!val.password || !val.username) {
      return message.open({
        type: "warning",
        content: "请输入用户名和密码",
      });
    } 
      //val.preventDefault(); // 阻止表单默认提交行为  
      try {  
        // 发送POST请求到后端，假设后端API的URL是'/api/login'  
        const response = await axios.post('http://localhost:8091/api/user/login', {  
          username: val.username,  
          password: val.password 
        });  
        // 如果登录成功，后端可能会返回一个token或其他信息  
        // 你可以在这里处理这些信息，例如保存到localStorage或导航到另一个页面
        if(response.data.code){
          console.log('登录成功:', response.data);  
          localStorage.setItem('role',response.data.data.role)
          localStorage.setItem('token',response.data.data.token)
          localStorage.setItem('username',response.data.data.username)
          const now = new Date();
          localStorage.setItem('lastLoginTime', now.toISOString());
          getMenu(response).then(({data})=>{
            // const aa=data.data.menu[0].path;
            navigate("/home")
            return message.open({
              type: "success",
              content: "登录成功",
            });
        }) 
        } else {
          console.log('登录失败:');  
          return message.open({
            type: "warning",
            content: "登录失败",
          });
        } 

        // 假设我们有一个导航函数，现在导航到主页 
   
        // navigateToHomePage();  
      } catch (error) {  
        // 处理错误，例如显示错误信息给用户  
        //setError(error.message || '登录失败');  
        return message.open({
          type: "warning",
          content: "出现错误",
        });
      }  
// login(val).then(({data})=>{
// console.log(data);
// })
  

  };
  const handleRegister = () => {
      navigate('/register');
  };
  return (
    <Form className="login-container" onFinish={handleSubmit}>
      <div className="login_title">系统登录</div>
      <Form.Item label="账号" name="username">
        <Input placeholder="请输入账号"></Input>
      </Form.Item>
      <Form.Item label="密码" name="password">
        <Input.Password placeholder="请输入密码"></Input.Password>
      </Form.Item>
      <div className="space-between"><Space>
      <Form.Item className="login-button">
       
        <Button type="primary" htmlType="submit">
          登录
        </Button>
      </Form.Item>
      <Form.Item className="register-button">
        <Button type="link" onClick={handleRegister}>
          注册
        </Button>
      </Form.Item> </Space></div>
    </Form>
  );
};
export default Login;
